/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-03-10 09:30:36
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-10 18:05:23
 * @Description: file content
 */

import { IncomingMessage } from "node:http";
import * as uuid from "uuid";

/**
 *处理请求url
 *
 * @export
 * @param {IncomingMessage["url"]} url
 * @return {*}
 */
export function handleRequestUrl(url: IncomingMessage["url"]) {
  const room = url?.split("?")[0] || "/";
  const wsuid =
    new URLSearchParams(url?.split("?")[1]).get("wsuid") || uuid.v4();

  return { room, wsuid };
}

/**
 *处理ws send 的数据格式。
 *
 * @export
 * @param {*} data
 * @return {*}
 */
export function handleWsSendData(data) {
  let ret;
  if (data == null) {
    return "null";
  }
  if (Array.isArray(data) || typeof data === "object") {
    try {
      ret = JSON.stringify(data);
    } catch (error) {
      ret = data.toString();
    }
  } else if (["string", "number", "boolean"].includes(typeof data)) {
    ret = data;
  } else {
    ret = data.toString ? data.toString() : data;
  }
  return ret;
}
